<?php


namespace app\controller\backend;


use app\model\Keyword;
use app\model\Website;
use app\service\ExcelService;
use app\service\MonitorService;
use app\validate\KeywordValidate;
use think\exception\ValidateException;
use think\response\Json;

class KeywordController extends BaseController
{
    public $header = ['关键词名称','关键词链接','关键词位置','关键词状态'];
    public $map = ['name','url','position','status'];

    /**
     * 读取数据列表
     * @return Json
     * @method Post
     * @error_number  0: 成功, -1: 数据库查询失败, -2: 请求方法错误, -3: 数据重复, -4：数据缺少或校验不通过,
     */
    public function index(Keyword $Keyword): Json
    {
        if (request()->isGet()) {
            $websiteId = (int)input('website_id', '', 'trim');
            if(!$websiteId){
                return jsonReturn(-1,'站点不能为空');
            }
            $where = [
                'website_id' => $websiteId,
                'seller_id' => $this->admin['seller_id'],
            ];
            $limit = $this->setLimit();
            $res = $Keyword->getKeywordList($where, $limit,'id,website_id,name,url,position,sort,baidu_pc,baidu_mob,three_pc,sougou_mob,status',['website']);
            return json(pageReturn($res));
        }

        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 读取数据
     * @return Json
     */
    public function read(Keyword $Keyword)
    {
        if (request()->isGet()) {
            $param = input('get.');
            try {
                validate(KeywordValidate::class)->scene('read')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $param['seller_id'] = $this->admin['seller_id'];

            $res = $Keyword->getKeyword($param);
            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 保存
     * @param Keyword $Keyword
     * @return Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Keyword $Keyword): Json
    {
        if (request()->isPost()) {
            $param = input('post.');

            try {
                validate(KeywordValidate::class)->scene('save')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $param['seller_id'] = $this->admin['seller_id'];
            $uniqueWhere = [
                'website_id' => $param['website_id'],
                'name' => $param['name'],
                'url' => $param['url']
            ];
            $Keyword->saveUnique($uniqueWhere,'关键词已经存在');

            $res = $Keyword->addKeyword($param);

            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 编辑
     * @param Keyword $Keyword
     * @return Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function update(Keyword $Keyword): Json
    {
        if (request()->isPost()) {
            $param = input('post.');

            try {
                validate(KeywordValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-4, $e->getMessage());
            }
            $uniqueWhere = [
                'website_id' => $param['website_id'],
                'name' => $param['name'],
                'url' => $param['url']
            ];
            $Keyword->updateUnique($uniqueWhere,$param['id'],'关键词已经存在');
            $updateWhere = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
                'website_id' => $param['website_id'],
            ];
            $res = $Keyword->updateKeyword($updateWhere,$param);

            return json($res);
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 删除数据
     * @return Json
     */
    public function delete(Keyword $Keyword): Json
    {
        if (request()->isPost()) {
            $param = input('post.');
            try {
                validate(KeywordValidate::class)->scene('delete')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-4, $e->getMessage());
            }

            if(empty($param['keyword_id'])){
                jsonReturn(0, '删除成功');
            }else{
                if(count($param['keyword_id'])){
                    $where = [
                        'id' => $param['keyword_id'][0],
                        'seller_id' => $this->admin['seller_id'],
                        'website_id' => $param['website_id']
                    ];
                }else{
                    $where = [
                        ['id' , 'in',$param['keyword_id']],
                        ['seller_id' ,'=', $param['seller_id']],
                        ['website_id', '=', $param['website_id']]
                    ];
                }
                $res = $Keyword->deleteKeyword($where);
                return json($res);
            }
        }
        return jsonReturn(-2, '请求方法错误');
    }

    /**
     * 导入关键词
     * @param ExcelService $excelService
     * @param Keyword $Keyword
     * @return Json
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     */
    public function import(ExcelService $excelService,Keyword $Keyword): Json
    {
        $param = input('post.');
        $param['file'] = request()->file('file');
        try {
            validate(KeywordValidate::class)->scene('import')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-4, $e->getMessage());
        }
        $data = $excelService->readData($param['file']);
        if(empty($data)){
            return jsonReturn(-1,'数据读取失败或者文件加为空，请检查');
        }
        $data = $this->checkData($data);
        if(isset($data['code'])){
            return json($data);
        }
        $data = $this->dealWithData($data,$param['website_id']);

        $res = $Keyword->addAllCustomData($data);

        return json($res);
    }

    /**
     * @param $data
     * @return array
     */
    public function checkData($data): array
    {
        $header = array_shift($data);
        if(count($header)  != 4){
            return dataReturn(-2,'数据格式错误，请参考样例');
        }
        $i = 0;
        foreach($header as $value){
            if($value != $this->header[$i]){
                return dataReturn(-3,'数据格式错误，请参考样例');
            }
            $i++;
        }
        return $data;
    }

    /**
     * @param $data
     * @param $siteId
     * @return array
     */
    public function dealWithData($data,$siteId): array
    {
        $tmpData = [];
        foreach($data as $val){
            if(!empty($val)){
                $tmp = ['website_id' => $siteId];
                $tmp['seller_id'] = $this->admin['seller_id'];
                $i = 0;
                foreach($val as $vv){
                    if($i == 0 && empty($vv)){
                        break;
                    }
                    if($i == 3){
                        if($vv == '正常'){
                            $vv = 1;
                        }else{
                            $vv = 2;
                        }
                    }
                    $tmp[$this->map[$i]] = $vv;
                    if($i == 3){
                        array_push($tmpData,$tmp);
                    }
                    $i++;
                }
            }
        }
        return $tmpData;
    }

    /**
     * 关键词模版
     * @return Json
     */
    public function template(): Json
    {
        return jsonReturn(0,'success',config('system.keyword_template_path'));
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function monitor(MonitorService $monitorService): Json
    {
        $param = input('get.');
        try {
            validate(KeywordValidate::class)->scene('monitor')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-4, $e->getMessage());
        }
        $param['seller_id'] = $this->admin['seller_id'];
        return $monitorService->getMonitorData($param);
    }

}